/*
 * @Author: yuanlai
 * @Date: 2024-08-18 11:04:05
 * @LastEditors: yuanlai
 * @LastEditTime: 2024-08-18 16:54:38
 * @Description: file content
 */
const fs = require('fs');
const path = require('path');
const globby = require('globby');
const { parse } = require('node-html-parser');
const urlRegex = require('url-regex');
// 获取外部链接的正则
const urlPattern = /(https?:\/\/[^/]*)/i;

const urls = new Set();
// 遍历dist目录所有html,js,css,获取所有外部链接
async function searchDomains() {
    const files = await globby('dist/**/*.{html,js,css}');
    for (const file of files) {
        const soure = fs.readFileSync(file, 'utf-8');
        const matches = soure.match(urlRegex({ soure: true }));
        if (matches) {
            matches.forEach((url) => {
                const match = url.match(urlPattern);
                if (match && match[1]) {
                    urls.add(match[1]);
                }
            })
        }
    }
}

// 将外部链接插入到html中
async function insertLinks() {
    const files = await globby('dist/**/*.html');
    const links = [...urls].map(url => `<link rel="dns-prefetch" href="${url}">`).join('\n');
    for (const file of files) {
        const html = fs.readFileSync(file, 'utf-8');
        const root = parse(html);
        const head = root.querySelector('head');
        head.insertAdjacentHTML('afterbegin', links);
        fs.writeFileSync(file, root.toString(), 'utf-8');
    }
}

async function main() {
    await searchDomains();
    await insertLinks();
}

main();